package com.darchrow.nio.file;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Scanner;

/**
 * @author mdl
 * @date 2020/5/27 15:48
 */
public class MapMemeryBuffer {

    public final static int Buffer_Size = 1024 * 1024 * 3;


    public static void readByMappedByteBuffer(String filePath, String destPath) {
        // map size 最大 Integer.MAX_VALUE (2G)

        // 512m
        long every_length = 1L << 29;
        // 4G
        long _4G = 1L << 32;


        File file = new File(filePath);

        long size = file.length();
        System.out.println(size);


        try {

            MappedByteBuffer mbb = new RandomAccessFile(file, "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, size);


            byte[] bytes = new byte[Buffer_Size];

            //模拟接收的ByteBuffer   size 10
            ByteBuffer byteBuffer = ByteBuffer.allocate(Buffer_Size);
            //用于临时存放Bytebuffer转换后的字符
            CharBuffer charBuffer = CharBuffer.allocate(Buffer_Size);
            //用于连接展示字符串
            StringBuilder sb = new StringBuilder();

            for (int offset = 0; offset < size; offset += Buffer_Size) {
                if (size - offset > Buffer_Size) {
                    for (int i = 0; i < Buffer_Size; i++) {
                        bytes[i] = mbb.get(offset + i);
                    }
                } else {
                    for (int i = 0; i < size - offset; i++) {
                        bytes[i] = mbb.get(offset + i);
                    }
                }
                // 将得到的3M内容给Scanner，这里的XXX是指Scanner解析的分隔符
//                Scanner scan = new Scanner(new ByteArrayInputStream(bytes))
//                        .useDelimiter(" ");
//                while (scan.hasNext()) {
//                    // 这里为对读取文本解析的方法
//                    System.out.print(scan.next() + " ");
//                }
//                scan.close();



            }



        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static void main(String[] args) throws Exception {
//        String sourePath ="H:\\重装系统\\系统镜像\\Windows_7_ X64.iso";
        String filePath = "D:\\selfstudy\\data.txt";
        readByMappedByteBuffer(filePath, "c");

    }


}
